<?php

namespace app\appv110\controller;

use app\appv110\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\appv110\model\Yuyue;
use app\appv110\model\CtmSpecial;
use app\appv110\model\Order;
use app\appv110\model\Staff;
use app\appv110\model\Store;
use app\appv110\model\ProvCityArea;
use app\appv110\model\MedicalAddress;
use app\appv110\model\StoreCtm;
use app\appv110\model\Custom;
use app\appv110\model\StaffNote;

class IndexController extends CommonController {
    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 50000  
         * 50001  
         * 50002  
         * 
         */
    }

    /*
     * 提示美容师备注
     * author xfwed
     * date 2019.12.05
     */

    public function hintStaffNote() {
        $rule = [
            'staff_id' => 'require',
        ];
        $msg = [
            'staff_id.require' => '美容师id必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $staff_id = $all['staff_id']; //美容师id
        $list = Yuyue::where('staff_id', $staff_id)
                ->where('status', 4)
                ->where('hint_note', 2)
                ->where('staff_time', '<', date('Y-m-d H:i:s', time() - 3600))
                ->field('id,ctm_id')
                ->select();
        if ($list) {
            $data = collection($list)->toArray();
            $ids = array_map('reset', $data);
            Yuyue::where('id', 'in', $ids)->update(['hint_note' => 1]);
        }
        $tmp_arr = array();

        foreach ($list as $k => $v) {
            if (in_array($v['ctm_id'], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($list[$k]);
            } else {
                $tmp_arr[] = $v['ctm_id'];
            }
        }
//        print_r($tmp_arr);
        sort($list); //sort函数对数组进行排序
        return Utils::ajaxReturn(0, '查询成功', $list);
    }
    
  /*
     * 服务人数
     * author xfwed
     * date 2020.08.06
     */

    public function serCtmNum() {
        $rule = [
            'store_id' => 'require',
            'type' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'store_id.require' => '店铺id必须',
            'type.require' => '时间类型必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $store_id = $all['store_id'];
        $type = $all['type']; // 0.本日 1.本周 2.本月 3.全部 4.自定义
        $startTime = input('param.startTime');
        $endTime = input('param.endTime');
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }
        $offset = ($page - 1) * $perPage;
        //php获取今日开始时间戳和结束时间戳
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        //php获取本周起始时间
        $beginWeek = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"));
        $endWeek = mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y"));
        //$beginWeek = time()- 60*60*24*7;
        //$endWeek = time();
        //php获取本月起始时间戳和结束时间戳
        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        if ($type == 0) {
            $where['y.staff_time'] = ['between', [date('Y-m-d H:i:s', $beginToday), date('Y-m-d H:i:s', $endToday)]];
        } elseif ($type == 1) {
            $where['y.staff_time'] = ['between', [date('Y-m-d H:i:s', $beginWeek), date('Y-m-d H:i:s', $endWeek)]];
        } elseif ($type == 2) {
            $where['y.staff_time'] = ['between', [date('Y-m-d H:i:s', $beginThismonth), date('Y-m-d H:i:s', $endThismonth)]];
        } elseif ($type == 4) {
            $where['y.staff_time'] = ['between', [$startTime, date('Y-m-d H:i:s', strtotime($endTime) + 24 * 60 * 60)]];
        }

        $where = isset($where) ? $where : [];
        $where['y.store_id'] = $store_id;
        $where['y.status'] = ['in', '4,7,8'];

        $num = Yuyue::alias('y')
                ->join('custom c', 'c.id = y.ctm_id', 'left')
                ->where($where)
                ->group('y.ctm_id')
                ->count();

        $allList = Yuyue::alias('y')
                ->join('custom c', 'c.id = y.ctm_id', 'left')
                ->where($where)
                ->group('y.ctm_id')
                ->limit($offset, $perPage)
                ->order('y.staff_time asc')
                ->field('y.ctm_id,c.custom_phone,c.custom_name,c.custom_photo,c.vip_status,c.is_smallshop,c.source_id,c.source_type')
                ->select();


        foreach ($allList as $k => $v) {
            $ctmOrder = Order::where('ctm_id', $v['ctm_id'])
                    ->where('status', 2)
                    //->where('store_id',$store_id)
                    //->where('type','in','1,2,5')
                    ->order('pay_time desc')
                    ->find();
            if ($ctmOrder) {
                $allList[$k]['pay_time'] = $ctmOrder['pay_time'];
            } else {
                $allList[$k]['pay_time'] = '';
            }
            //查询用户是否为逆行者
            $medicalData = MedicalAddress::where('ctm_id', $v['ctm_id'])->count();
            if ($medicalData > 0) {
                $is_medical = 1;
            } else {
                $is_medical = 2;
            }
            $allList[$k]['is_medical'] = $is_medical;

            if ($v['vip_status'] == 2 || $v['vip_status'] == 3) {
                $specialTime = CtmSpecial::where('ctm_id', $v['ctm_id'])->order('id asc')->find();
                if ($specialTime['type'] == 3) {
                    $allList[$k]['vip_status'] = 4; //4逆行者特权 5i美优优特权 
                } else {
                    $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $v['ctm_id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id', '<>', 0)
                            ->group('ctm_id')
                            ->count();
                    if ($specialOrder > 0) {
                        $allList[$k]['vip_status'] = 5; //4逆行者特权 5i美优优特权 
                    }
                }
            }

            if ($v['source_type'] == 0) {
                $sourceName = '';
            } elseif ($v['source_type'] == 1) {
                $sourceName = '平台引流';
            } elseif ($v['source_type'] == 2) {
                $staffName = Staff::where('id', $v['source_id'])->value('staff_name');
                $sourceName = '美容师' . $staffName;
            } elseif ($v['source_type'] == 3) {
                $StoreRow = Store::where('id', $v['source_id'])->field('store_name,city')->find();
                $cityName = ProvCityArea::where('id', $StoreRow['city'])->value('name');
                $sourceName = $cityName . '的' . $StoreRow['store_name'];
            } elseif ($v['source_type'] == 4) {
                $sourceName = '小店转介绍';
            }
            $allList[$k]['sourceName'] = $sourceName;
            //查询用户是否在本店开通的特权
            $orderRow = Order::where('type', 4)
                    ->where('ctm_id', $v['ctm_id'])
                    ->where('status', 2)
                    ->where('store_id', $store_id)
                    ->order('id desc')
                    ->find();
            if ($orderRow) {
                $allList[$k]['is_exclusive'] = 1; //1是2否绑定的该店铺  显示 专属特权
            } else {
                $allList[$k]['is_exclusive'] = 2;
            }
        }

        $data['num'] = $num;
        $data['list'] = $allList;
        return Utils::ajaxReturn(0, '成功', $data);
    }

    /*
     * 新增客户
     * author xfwed
     * date 2020.08.06
     */

    public function storeNewCtm() {
        $rule = [
            'store_id' => 'require',
            'type' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'store_id.require' => '店铺id必须',
            'staff_id.require' => '美容师id必须',
            'type.require' => '时间类型必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '当前页数为数字',
            'page.egt' => '当前页数最小为1',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $store_id = $all['store_id'];
        $type = $all['type']; //0全部1今日2本周3本月4自定义  0.本日 1.本周 2.本月 3.全部 4.自定义
        $startTime = input('param.startTime');
        $endTime = input('param.endTime');
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }
        $offset = ($page - 1) * $perPage;
        //php获取今日开始时间戳和结束时间戳
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        //php获取本周起始时间
        $beginWeek = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"));
        $endWeek = mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y"));
        //$beginWeek = time()- 60*60*24*7;
        //$endWeek = time();
        //php获取本月起始时间戳和结束时间戳
        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        
        if ($type == 0) {
            $where1['s.add_time'] = ['between', [date('Y-m-d H:i:s', $beginToday), date('Y-m-d H:i:s', $endToday)]];
            $begin = $beginToday;
            $end = $endToday;
            
        } elseif ($type == 1) {
            //return Utils::ajaxReturn(0, '666', date('Y-m-d H:i:s',$beginWeek).'-------------'.date('Y-m-d H:i:s',$endWeek));
            $where1['s.add_time'] = ['between', [date('Y-m-d H:i:s', $beginWeek), date('Y-m-d H:i:s', $endWeek)]];
            $begin = $beginWeek;
            $end = $endWeek;
        } elseif ($type == 2) {
            $where1['s.add_time'] = ['between', [date('Y-m-d H:i:s', $beginThismonth), date('Y-m-d H:i:s', $endThismonth)]];
            $begin = $beginThismonth;
            $end = $endThismonth;
            
        } elseif ($type == 4) {
            //$where1['s.add_time'] = ['between',[$startTime,date('Y-m-d H:i:s',strtotime($endTime)+24*60*60)]];
            $where1['s.add_time'] = ['between', [$startTime, $endTime]];
            $begin = $startTime;
            $end = $endTime;
            
        }elseif ($type == 3) {
            $begin = '1993-01-01';
            $end = '2060-01-01';
        }


        $where1 = isset($where1) ? $where1 : [];
        $where['s.store_id'] = $store_id;
        $ids = StoreCtm::alias('s')
                //->join('staff st', 'st.id = s.staff_id', 'left')
                ->where($where)
                ->field('MIN(s.id),MIN(s.add_time)')
                ->group('s.ctm_id')
                //->order('s.id asc')
                ->column('s.id');
        //print_r($ids->toArray());
        $sql = "SELECT id FROM (
            SELECT MIN(id) id,MIN(add_time) add_time,ctm_id,store_id
            FROM ai_store_ctm
            WHERE store_id = " . $store_id . " GROUP BY ctm_id
        ) AS a
        WHERE 1=1
        AND a.add_time >= ".$begin." AND a.add_time >= ".$end."
        ";
        $res = Db::query($sql);
        foreach ($res as $k => $v) {
            $ids6[] = $v['id'];
        }
        //$ids6 = substr($ids6,0,strlen($ids6)-1);
        //print_r($ids6);
        $num = StoreCtm::alias('s')
                ->where($where1)
                ->where('s.id', 'in', $ids6)
//                ->limit($offset, $perPage)
                ->order('s.add_time asc')
                ->field('s.ctm_id,s.add_time')
                ->count();

        $allList = StoreCtm::alias('s')
                ->where($where1)
                ->where('s.id', 'in', $ids6)
                ->limit($offset, $perPage)
                ->order('s.add_time asc')
                ->field('s.ctm_id,s.add_time')
                ->select();
        //print_r(StoreCtm::getLastSql());
        foreach ($allList as $k => $v) {
            $ctmRow = Custom::where('id', $v['ctm_id'])
                    ->field('id,custom_phone,custom_name,custom_photo,vip_status,is_smallshop,source_type,source_id')
                    ->find();
            if ($ctmRow['vip_status'] == 2 || $ctmRow['vip_status'] == 3) {
                $specialTime = CtmSpecial::where('ctm_id', $ctmRow['id'])->order('id asc')->find();
                if ($specialTime['type'] == 3) {
                    $allList[$k]['vip_status'] = 4; //4逆行者特权 5i美优优特权 
                } else {
                    $specialOrder = Order::alias('o')
                            ->where('o.ctm_id', '=', $ctmRow['id'])
                            ->where('o.status', 2)
                            ->where('o.type', 4)
                            ->where('o.mini_shop_id', '<>', 0)
                            ->group('ctm_id')
                            ->count();
                    if ($specialOrder > 0) {
                        $allList[$k]['vip_status'] = 5; //4逆行者特权 5i美优优特权 
                    }
                }
            }

            if ($ctmRow['source_type'] == 0) {
                $sourceName = '';
            } elseif ($ctmRow['source_type'] == 1) {
                $sourceName = '平台引流';
            } elseif ($ctmRow['source_type'] == 2) {
                $staffName = Staff::where('id', $ctmRow['source_id'])->value('staff_name');
                $sourceName = '美容师' . $staffName;
            } elseif ($ctmRow['source_type'] == 3) {
                $StoreRow = Store::where('id', $ctmRow['source_id'])->field('store_name,city')->find();
                $cityName = ProvCityArea::where('id', $StoreRow['city'])->value('name');
                $sourceName = $cityName . '的' . $StoreRow['store_name'];
            } elseif ($ctmRow['source_type'] == 4) {
                $sourceName = '小店转介绍';
            }
            $allList[$k]['sourceName'] = $sourceName;
            $allList[$k]['is_smallshop'] = $ctmRow['is_smallshop'];
            $allList[$k]['custom_phone'] = $ctmRow['custom_phone'];
            $allList[$k]['custom_name'] = $ctmRow['custom_name'];
            $allList[$k]['custom_photo'] = $ctmRow['custom_photo'];
            $allList[$k]['vip_status'] = $ctmRow['vip_status'];
            $pay_time = Order::where('ctm_id', $v['ctm_id'])
                    ->where('status', 2)
                    //->where('pay_money', '>', 0)
                    //->where('store_id',$store_id)
                    ->order('pay_time desc')
                    ->value('pay_time');
            $allList[$k]['pay_time'] = $pay_time;
            //查询用户是否在本店开通的特权
            $orderRow = Order::where('type', 4)
                    ->where('ctm_id', $v['ctm_id'])
                    ->where('status', 2)
                    ->where('store_id', $store_id)
                    ->order('id desc')
                    ->find();
            if ($orderRow) {
                $allList[$k]['is_exclusive'] = 1; //1是2否绑定的该店铺  显示 专属特权
            } else {
                $allList[$k]['is_exclusive'] = 2;
            }
        }
        $data['num'] = $num;
        $data['list'] = $allList;
        return Utils::ajaxReturn(0, '成功', $data);
    }

}
